import 'package:dailoz/entity/task_day_entity.dart';
import 'package:dailoz/entity/task_total_time_entity.dart';
import 'package:dailoz/size_config.dart';
import 'package:dailoz/view_model/analyze_page_view_model.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';

class AnalyzeService {
  static bool validate(List<dynamic> taskDayList) {
    bool numIsEmpty = true;
    for (var element in taskDayList) {
      TaskDayEntity taskDayEntity = TaskDayEntity.fromJson(element);
      if (taskDayEntity.num == 0 && numIsEmpty != false) {
        numIsEmpty = true;
      } else {
        numIsEmpty = false;
      }
    }
    return numIsEmpty;
  }

  // 生成柱状图
  static BarChartData mainBarChartData(List<dynamic> taskTotalTimeList) {
    final maxValue = taskTotalTimeList
        .map((e) => e['total'])
        .reduce((value, element) => value > element ? value : element);
    return BarChartData(
      minY: 0,
      maxY: maxValue / 10 + 20,
      gridData: FlGridData(
        drawHorizontalLine: true,
        getDrawingHorizontalLine: (value) {
          return FlLine(
            color: Colors.grey,
            strokeWidth: 1,
          );
        },
        getDrawingVerticalLine: (value) {
          return FlLine(
            color: Colors.grey,
            strokeWidth: 0,
          );
        },
        show: true,
      ),
      barGroups: _barChartData(taskTotalTimeList),
      titlesData: FlTitlesData(
        show: true,
        bottomTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            getTitlesWidget: (value, tt) {
              final date = DateTime.fromMillisecondsSinceEpoch(value.toInt());
              return Text('${date.month}/${date.day}');
            },
          ),
        ),
        topTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: false,
          ),
        ),
        leftTitles: AxisTitles(
          sideTitles: SideTitles(
              showTitles: true,
              reservedSize: 20,
              getTitlesWidget: (value, _) {
                return Container(
                  padding: EdgeInsets.only(
                    top: SizeConfig.getProportionateScreenHeight(10),
                  ),
                  child: Text("${value.toInt()}"),
                );
              }),
          axisNameWidget: const Text(
            "hour*10",
            style: TextStyle(color: Colors.red),
          ),
          axisNameSize: 20.0,
        ),
        rightTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            reservedSize: 20,
            getTitlesWidget: (value, _) {
              return Container(
                padding: EdgeInsets.only(
                  top: SizeConfig.getProportionateScreenHeight(10),
                ),
                child: Text("${value.toInt()}"),
              );
            },
          ),
        ),
      ),
    );
  }

  static List<BarChartGroupData>? _barChartData(
      List<dynamic> taskTotalTimeList) {
    List<BarChartGroupData> barChartDataList = [];
    for (int index = 0; index < taskTotalTimeList.length; index++) {
      TaskTotalTimeEntity taskTotalTimeEntity =
          TaskTotalTimeEntity.fromJson(taskTotalTimeList[index]);
      barChartDataList.add(
        BarChartGroupData(
          x: DateTime.parse(taskTotalTimeEntity.time)
              .millisecondsSinceEpoch
              .toInt(),
          barsSpace: 3,
          barRods: [
            BarChartRodData(toY: taskTotalTimeEntity.total / 10, width: 10),
          ],
        ),
      );
    }
    return barChartDataList;
  }

  // 生成折线图
  static LineChartData mainData(List<dynamic> taskList, bool isCurved,
      List<bool> lineIsShow, List<Color> gradientColors) {
    return LineChartData(
      borderData: FlBorderData(
        border: const Border(
          top: BorderSide.none,
          right: BorderSide.none,
          left: BorderSide.none,
          bottom: BorderSide.none,
        ),
      ),
      gridData: FlGridData(
        drawHorizontalLine: true,
        getDrawingHorizontalLine: (value) {
          return FlLine(
            color: Colors.grey,
            strokeWidth: 1,
          );
        },
        getDrawingVerticalLine: (value) {
          return FlLine(
            color: Colors.grey,
            strokeWidth: 0,
          );
        },
        show: true,
      ),
      minX: 0,
      maxX: 11,
      minY: 0,
      maxY: 11,
      titlesData: FlTitlesData(
        show: true,
        topTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: false,
          ),
        ),
        rightTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: false,
          ),
        ),
        leftTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            getTitlesWidget: (value, _) {
              if (value % 2 == 0) {
                return Text('${value.toInt()}');
              }
              return const Text("");
            },
          ),
        ),
        bottomTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            reservedSize: 22,
            getTitlesWidget: (value, _) {
              if (value % 2 == 0) {
                return Text('${value.toInt() + 1}月');
              }
              return const Text("");
            },
          ),
        ),
      ),
      lineBarsData: lineBarData(taskList, isCurved, lineIsShow, gradientColors),
      lineTouchData: LineTouchData(
        touchTooltipData: LineTouchTooltipData(
          tooltipBgColor: Colors.black,
        ),
      ),
    );
  }

  static List<LineChartBarData> lineBarData(List<dynamic> taskList,
      bool isCurved, List<bool> lineIsShow, List<Color> gradientColors) {
    // bool isCurved = false;

    List<LineChartBarData> lineChartBarDataList = [];
    for (int index = 0; index < taskList.length; index++) {
      List<dynamic> valueList = taskList[index].values.toList();
      valueList.removeAt(0);
      lineChartBarDataList.add(
        LineChartBarData(
          show: lineIsShow[index],
          spots: List.generate(valueList.length, (index) {
            return FlSpot(
              index.toDouble(),
              valueList[index].toDouble() / 10,
            );
          }),
          dotData: FlDotData(
            show: false,
          ),
          isCurved: isCurved,
          color: gradientColors[index],
          belowBarData: BarAreaData(
            show: true,
            gradient: LinearGradient(
              colors: gradientColors.map((e) => e.withOpacity(0.3)).toList(),
            ),
            // color: LinearGradient,
          ),
        ),
      );
    }
    return lineChartBarDataList;
  }

  // 生成饼图
  static PieChartData mainTagPieChart(AnalyzePageViewModel provider) {
    return PieChartData(
      pieTouchData: PieTouchData(touchCallback: (_, pieTouchResponse) {
        if (pieTouchResponse?.touchedSection is FlLongPressEnd ||
            pieTouchResponse?.touchedSection is FlPanEndEvent) {
          provider.changeTagTouchedIndex(-1);
        } else {
          provider.changeTagTouchedIndex(
              pieTouchResponse?.touchedSection?.touchedSectionIndex);
        }
      }),
      centerSpaceRadius: 50.0,
      sections: List.generate(provider.tagList.length, (index) {
        final isTouched = index == provider.tagTouchedIndex;
        final double fontSize = isTouched ? 20 : 14;
        final double radius = isTouched ? 80 : 60;
        return PieChartSectionData(
          color: provider.colors[index % provider.colors.length],
          value: double.parse(
            provider.tagList[index]['num'].toString(),
          ),
          title: isTouched
              ? double.parse(
                  provider.tagList[index]['num'].toString(),
                ).toString()
              : provider.tagList[index]['title'].length > 8
                  ? provider.tagList[index]['title'].substring(0, 7) + '...'
                  : provider.tagList[index]['title'],
          radius: radius,
          titleStyle: TextStyle(
            fontSize: fontSize,
            fontWeight: FontWeight.bold,
            color: const Color(0xff000000),
            overflow: TextOverflow.ellipsis,
          ),
        );
      }),
    );
  }
}
